package com.fang.transfer.file.listener;

import com.fang.transfer.file.ThreadContext;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.common.NettyHandle;
import com.fang.transfer.file.common.RequestListener;
import com.fang.transfer.file.common.code.ServiceSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;
import com.fang.transfer.file.common.model.User;
import com.fang.transfer.file.service.FileSendRequestService;
import com.fang.transfer.file.service.UserService;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 发送文件请求
 */
@Service
public class SendFileRequestListener extends RequestListener<TransferFileRequest> {


    @Autowired
    private UserService userService;

    @Autowired
    private FileSendRequestService fileSendRequestService;

    @Autowired
    private NettyHandle nettyHandle;

    @Override
    public void handle(TransferFileRequest param) {
        ChannelHandlerContext handlerContext = ThreadContext.getChannelHandlerContext();
        String id = handlerContext.channel().id().toString();
        User sendUser = userService.getById(id);
        User receiveUser = userService.getById(param.getReceiveUser().getId());
        param.setSendUser(sendUser);
        param.setReceiveUser(receiveUser);
        fileSendRequestService.addRequest(param);
        nettyHandle.send(receiveUser.getId(), ServiceSendCode.SEND_FILE_REQUEST_RECEIVE_USER, param);
    }

    @Override
    public String getCode() {
        return ClientSendCode.SEND_FILE_REQUEST;
    }
}
